package de.distmlp.preprocessing.data;

import java.util.Iterator;

import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector.Element;

public class MLDataEntry {

	private final RandomAccessSparseVector targetVector;
	private final RandomAccessSparseVector featureVector;
	private final int featurevectorSize;
	private final int targetVectorSize;

	public MLDataEntry(final int nbInputUnits, final int nbOutputUnits) {
		this.featurevectorSize = nbInputUnits;
		this.targetVectorSize = nbOutputUnits;
		this.targetVector = new RandomAccessSparseVector(nbOutputUnits);
		this.featureVector = new RandomAccessSparseVector(nbInputUnits);
	}

	public void addInput(final int nb, final double value) {
		this.featureVector.set(nb, value);
	}

	public void addOutput(final int nb, final double value) {
		this.targetVector.set(nb, value);
	}

	public double[] getOutput() {
		final double[] output = new double[this.targetVectorSize];

		final Iterator<Element> iterator = this.targetVector.iterator();
		while (iterator.hasNext()) {
			final Element el = iterator.next();
			output[el.index()] = el.get();
		}
		return output;
	}

	public double[] getInput() {
		final double[] input = new double[this.featurevectorSize];

		final Iterator<Element> iterator = this.featureVector.iterator();
		while (iterator.hasNext()) {
			final Element el = iterator.next();
			input[el.index()] = el.get();
		}
		return input;
	}

	public int getFeaturevectorSize() {
		return this.featurevectorSize;
	}

	public int getTargetVectorSize() {
		return this.targetVectorSize;
	}

	@Override
	public String toString() {
		String output = "";
		final String feature = MLDataEntry.arraytoString(this.getInput());
		final String target = MLDataEntry.arraytoString(this.getOutput());
		if (feature.isEmpty() || target.isEmpty()) {
			return null;
		}
		output = target + "|" + feature;
		return output;
	}

	private static String arraytoString(final double[] data) {
		String output = "";
		if (data.length > 1) {
			for (int i = 0; i < data.length; i++) {
				if (data[i] != 0) {
					output += i + ":" + data[i] + " ";
				}
			}
		} else {
			output = 0 + ":" + data[0];
		}

		output = output.trim();
		return output;
	}

}
